import React, { useState, useEffect } from 'react';
import ControlPanel from './components/ControlPanel';
import ViewerLayout from './components/ViewerLayout';
import Login from './components/Login';
import UserInfo from './components/UserInfo';
import AdminPanel from './components/AdminPanel';
import ProcessingProgress from './components/ProcessingProgress';
import CompletionToast from './components/CompletionToast';
import { DicomService } from './services/DicomService';
import { ImageProcessor } from './services/ImageProcessor';
import { DicomExportService } from './services/DicomExportService';
import authService from './services/authService';
import faviconIcon from './assets/icons/favicon(1).png';
import './App.css';

function App() {
  // 认证状态
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [authLoading, setAuthLoading] = useState(true);
  const [showAdminPanel, setShowAdminPanel] = useState(false);
  
  // 原有状态
  const [dicomData, setDicomData] = useState(null);
  const [processedImages, setProcessedImages] = useState({
    ttp: null,
    mtt: null,
    ph: null,
    auc: null
  });
  const [isProcessing, setIsProcessing] = useState(false);
  const [processingProgress, setProcessingProgress] = useState(0);
  const [processingStep, setProcessingStep] = useState('');
  const [showCompletionToast, setShowCompletionToast] = useState(false);
  const [currentTool, setCurrentTool] = useState('pan');
  const [error, setError] = useState(null);
  const [enableInvert, setEnableInvert] = useState(true); // 默认启用反转，适用于DSA图像
  const [colorMap, setColorMap] = useState('jet'); // 默认使用jet颜色映射
  const [isDownloading, setIsDownloading] = useState(false);
  const [enableInterpolation, setEnableInterpolation] = useState(true); // 默认启用插值
  const [frameRange, setFrameRange] = useState({ start: 1, end: 1 }); // 起始帧和终止帧
  const [enableVesselExtraction, setEnableVesselExtraction] = useState(false); // 血管区域提取
  const [currentVesselMask, setCurrentVesselMask] = useState(null); // 当前的血管mask
  const [tdcMode, setTdcMode] = useState(false); // TDC分析模式状态
  const [vesselMode, setVesselMode] = useState(false); // 血管提取模式状态
  const [processingMethod, setProcessingMethod] = useState('normal'); // 处理方法：normal | maximum_slope
  const [arterialInputPoint, setArterialInputPoint] = useState(null); // 动脉输入点标记
  const [tdcChartData, setTdcChartData] = useState([]); // TDC图表数据
  // 删除isFooterVisible状态，footer现在固定显示

  // 检查是否有动脉输入点（用于最大斜率法验证）
  const hasArterialInputPoint = arterialInputPoint !== null;

  // 初始化认证状态
  useEffect(() => {
    const initAuth = async () => {
      try {
        const authResult = await authService.initializeAuth();
        setIsAuthenticated(authResult.isAuthenticated);
        setCurrentUser(authResult.user || null);
      } catch (error) {
        console.error('认证初始化失败:', error);
        setIsAuthenticated(false);
        setCurrentUser(null);
      } finally {
        setAuthLoading(false);
      }
    };

    initAuth();
  }, []);

  // 键盘快捷键
  useEffect(() => {
    if (!isAuthenticated) return;

    const handleKeyDown = (event) => {
      if (event.ctrlKey) {
        switch (event.key.toLowerCase()) {
          case 'o':
            event.preventDefault();
            handleLoadDicom();
            break;
          case 'p':
            event.preventDefault();
            if (dicomData && !isProcessing) {
              handleProcess();
            }
            break;
          case 's':
            event.preventDefault();
            const hasProcessedData = Object.values(processedImages).some(data => data);
            if (hasProcessedData && !isDownloading) {
              handleDownloadResults();
            }
            break;
          case 'i':
            event.preventDefault();
            setEnableInterpolation(prev => !prev);
            break;
          default:
            break;
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [dicomData, isProcessing, processedImages, isDownloading, isAuthenticated]);

  // 添加全局测试导出函数
  useEffect(() => {
    window.testDicomExport = async (processedImages, metadata) => {
      try {
        console.log('开始测试DICOM导出...', { processedImages, metadata });
        
        // 找到第一个有效的处理结果进行测试
        const validEntry = Object.entries(processedImages).find(([key, value]) => value && value.data);
        
        if (!validEntry) {
          alert('没有可用的处理结果进行测试');
          return;
        }
        
        const [parameterName, parameterData] = validEntry;
        console.log(`测试导出 ${parameterName} 参数...`);
        
        // 创建DICOM文件
        const dicomArrayBuffer = await DicomExportService.createDicomFromParameterData(
          parameterData,
          parameterName,
          metadata,
          new Date().toISOString().replace(/[:.]/g, '-')
        );
        
        // 验证生成的DICOM文件
        const isValid = await DicomExportService.validateDicomFile(dicomArrayBuffer);
        
        if (isValid) {
          // 如果验证成功，则保存文件
          const filename = await DicomExportService.exportSingleDicom(
            parameterData,
            parameterName,
            metadata
          );
          
          console.log('测试导出成功:', filename);
          alert(`✅ 测试导出成功: ${filename}\n\n✅ DICOM文件验证通过\n📋 请在医学图像查看器中验证文件是否可以正常打开。\n\n文件信息:\n- 参数: ${parameterName}\n- 尺寸: ${parameterData.width}×${parameterData.height}\n- 数据类型: ${parameterData.data.constructor.name}`);
        } else {
          console.error('DICOM文件验证失败');
          alert('❌ DICOM文件验证失败，文件可能无法正常使用');
        }
        
      } catch (error) {
        console.error('测试导出失败:', error);
        alert(`❌ 测试导出失败: ${error.message}\n\n请检查:\n1. 是否有处理结果数据\n2. 数据格式是否正确\n3. 浏览器控制台是否有详细错误信息`);
      }
    };
    
    // 清理函数
    return () => {
      delete window.testDicomExport;
    };
  }, []);

  const handleLoadDicom = async () => {
    try {
      setError(null);
      
      const input = document.createElement('input');
      input.type = 'file';
      input.multiple = true;
      input.accept = '.dcm,.dicom,.*'; // 扩展接受所有文件类型，因为DICOM文件可能没有扩展名
      
      input.onchange = async (event) => {
        const files = Array.from(event.target.files);
        if (files.length === 0) return;
        
        console.log(`选择了 ${files.length} 个文件`);
        
        try {
          const dicomSeries = await DicomService.loadDicomSeries(files);
          setDicomData(dicomSeries);
          
          // 清除之前的所有分析数据和状态
          console.log('清空之前的分析数据...');
          
          // 1. 清除处理结果
          setProcessedImages({
            ttp: null,
            mtt: null,
            ph: null,
            auc: null,
            cbf: null,
            cbv: null
          });
          
          // 2. 清除动脉输入点和处理方法
          setArterialInputPoint(null);
          setProcessingMethod('normal'); // 重置为默认方法
          
          // 3. 清除血管相关状态
          setCurrentVesselMask(null);
          setEnableVesselExtraction(false);
          
          // 4. 退出特殊模式
          setTdcMode(false);
          setVesselMode(false);
          
          // 5. 重置工具和视图状态
          setCurrentTool('pan'); // 重置为默认工具
          
          // 6. 清除TDC图表数据
          setTdcChartData([]);
          
          // 7. 清除处理状态
          setIsProcessing(false);
          setProcessingProgress(0);
          setProcessingStep('');
          setShowCompletionToast(false);
          setIsDownloading(false);
          
          // 8. 清除错误信息
          setError(null);
          
          // 更新帧范围默认值
          const totalFrames = dicomSeries.isMultiFrame 
            ? dicomSeries.metadata.numberOfFrames 
            : dicomSeries.images?.length || 1;
          setFrameRange({ start: 1, end: totalFrames });
          
          if (dicomSeries.isMultiFrame) {
            console.log(`多帧DICOM文件加载完成: ${dicomSeries.metadata.numberOfFrames} 帧`);
          } else {
            console.log(`DICOM序列加载完成: ${files.length} 个文件`);
          }
          
          console.log('新数据加载完成，已清空所有之前的分析结果');
        } catch (error) {
          console.error('DICOM加载失败:', error);
          setError('DICOM加载失败: ' + error.message);
        }
      };
      
      input.click();
    } catch (error) {
      console.error('打开文件对话框失败:', error);
      setError('打开文件对话框失败: ' + error.message);
    }
  };

  const handleProcess = async () => {
    if (!dicomData) {
      setError('没有可处理的DICOM数据');
      return;
    }

    try {
      setError(null);
      setIsProcessing(true);
      setProcessingProgress(0);
      setProcessingStep('初始化...');
      setShowCompletionToast(false);
      
      console.log('开始图像处理...', { 
        enableInvert, 
        frameRange, 
        enableVesselExtraction, 
        processingMethod, 
        arterialInputPoint 
      });

      // 验证最大斜率法的动脉输入点
      if (processingMethod === 'maximum_slope') {
        console.log('使用最大斜率法，验证动脉输入点');
        console.log('arterialInputPoint:', arterialInputPoint);
        console.log('hasArterialInputPoint:', hasArterialInputPoint);
        
        if (!arterialInputPoint) {
          console.error('最大斜率法缺少动脉输入点');
          setError('最大斜率法需要标记动脉输入点');
          setIsProcessing(false);
          setProcessingProgress(0);
          setProcessingStep('');
          return;
        }
      }

      // 进度回调函数
      const onProgress = (progress, step) => {
        setProcessingProgress(progress);
        setProcessingStep(step);
      };

      const processor = new ImageProcessor(dicomData, { 
        enableInvert, 
        frameRange,
        enableVesselExtraction,
        vesselMask: currentVesselMask, // 传递当前的血管mask
        processingMethod, // 传递处理方法
        arterialInputPoint, // 传递动脉输入点
        onProgress // 传递进度回调
      });
      const results = await processor.processAll();

      setProcessedImages(results);
      setProcessingProgress(100);
      setProcessingStep('处理完成');
      
      // 显示完成提示
      setShowCompletionToast(true);
      setTimeout(() => {
        setShowCompletionToast(false);
      }, 3000); // 3秒后自动隐藏
      
      console.log('图像处理完成:', results);
    } catch (error) {
      console.error('图像处理失败:', error);
      setError('图像处理失败: ' + error.message);
      setProcessingProgress(0);
      setProcessingStep('');
    } finally {
      setTimeout(() => {
        setIsProcessing(false);
        setProcessingProgress(0);
        setProcessingStep('');
      }, 1500); // 延迟一点时间让用户看到100%完成状态
    }
  };

  const handleDownloadResults = async () => {
    const hasProcessedData = Object.values(processedImages).some(data => data);
    if (!hasProcessedData) {
      setError('没有可下载的处理结果');
      return;
    }

    try {
      setError(null);
      setIsDownloading(true);
      console.log('开始下载处理结果...');

      // 过滤掉空的处理结果
      const validResults = {};
      Object.entries(processedImages).forEach(([key, value]) => {
        if (value && value.data) {
          validResults[key] = value;
        }
      });

      // 获取当前的TDC标记（从ViewerLayout获取）
      let currentTdcMarkers = null;
      try {
        // 尝试从ViewerLayout组件获取TDC标记
        const sessionKey = dicomData ? getDicomSessionKey(dicomData) : null;
        if (sessionKey) {
          const savedData = localStorage.getItem(sessionKey);
          if (savedData) {
            const markersData = JSON.parse(savedData);
            if (markersData.markers && Array.isArray(markersData.markers)) {
              currentTdcMarkers = markersData.markers;
              console.log(`发现 ${currentTdcMarkers.length} 个TDC标记，将导出为LabelSet`);
            }
          }
        }
      } catch (error) {
        console.warn('获取TDC标记失败:', error);
      }

      const filename = await DicomExportService.exportProcessedResults(
        validResults, 
        dicomData?.metadata,
        currentVesselMask, // 传递血管Mask
        currentTdcMarkers,  // 传递TDC标记
        {
          processingMethod: processingMethod,
          arterialInputPoint: arterialInputPoint,
          dicomData: dicomData, // 传递完整的dicomData以便JSON导出使用
          chartData: tdcChartData  // 传递TDC图表数据用于统计计算
        }
      );

      console.log(`下载完成: ${filename}`);
      
      // 显示成功消息，包含额外导出内容的提示
      let successDetails = [`成功下载 ${filename}`];
      if (currentVesselMask) {
        successDetails.push('✓ 包含血管Mask (NIfTI格式)');
      }
      if (currentTdcMarkers && currentTdcMarkers.length > 0) {
        successDetails.push(`✓ 包含TDC标记LabelSet (${currentTdcMarkers.length}个标记, NIfTI格式)`);
      }
      
      // 临时显示成功消息，然后清除
      setTimeout(() => {
        // 可以在这里添加成功提示的UI逻辑
      }, 3000);

    } catch (error) {
      console.error('下载失败:', error);
      setError('下载失败: ' + error.message);
    } finally {
      setIsDownloading(false);
    }
  };

  // 辅助函数：生成DICOM会话密钥（与ViewerLayout中的逻辑保持一致）
  const getDicomSessionKey = (dicomData) => {
    if (!dicomData) return null;
    
    const seriesUID = dicomData.seriesInstanceUID || 'unknown';
    const imageCount = dicomData.images?.length || 0;
    const firstImageTime = dicomData.images?.[0]?.acquisitionTime || 'unknown';
    
    return `tdc_markers_${seriesUID}_${imageCount}_${firstImageTime}`;
  };

  const handleInvertChange = (invert) => {
    setEnableInvert(invert);
    console.log('图像反转设置已更改:', invert);
  };

  const handleColorMapChange = (newColorMap) => {
    setColorMap(newColorMap);
    console.log('颜色映射已更改:', newColorMap);
  };

  const handleInterpolationChange = (interpolation) => {
    setEnableInterpolation(interpolation);
    console.log('图像插值设置已更改:', interpolation);
  };

  const handleFrameRangeChange = (newFrameRange) => {
    setFrameRange(newFrameRange);
    console.log('帧范围设置已更改:', newFrameRange);
  };

  const handleVesselExtractionChange = (enabled) => {
    setEnableVesselExtraction(enabled);
    console.log('血管区域提取设置已更改:', enabled);
  };

  const handleProcessingMethodChange = (method) => {
    setProcessingMethod(method);
    console.log('处理方法已更改:', method);
    console.log('hasArterialInputPoint:', hasArterialInputPoint);
    
    // 如果切换到普通方法，清除动脉输入点
    if (method === 'normal') {
      setArterialInputPoint(null);
    }
  };

  const handleArterialInputPointChange = (point) => {
    console.log('handleArterialInputPointChange 被调用, point:', point);
    setArterialInputPoint(point);
    console.log('arterialInputPoint 状态已更新');
  };

  // 处理TDC图表数据更新
  const handleTdcChartDataUpdate = (chartData) => {
    setTdcChartData(chartData || []);
    console.log('TDC图表数据已更新:', chartData?.length || 0, '个数据集');
  };

  // 认证处理函数
  const handleLoginSuccess = () => {
    const initAuth = async () => {
      try {
        const authResult = await authService.initializeAuth();
        setIsAuthenticated(authResult.isAuthenticated);
        setCurrentUser(authResult.user);
      } catch (error) {
        console.error('登录后认证初始化失败:', error);
      }
    };
    initAuth();
  };

  const handleLogout = () => {
    setIsAuthenticated(false);
    setCurrentUser(null);
    setShowAdminPanel(false);
    // 清除应用数据
    setDicomData(null);
    setProcessedImages({
      ttp: null,
      mtt: null,
      ph: null,
      auc: null
    });
    setError(null);
  };

  const handleOpenAdminPanel = () => {
    setShowAdminPanel(true);
  };

  const handleCloseAdminPanel = () => {
    setShowAdminPanel(false);
  };

  // 如果正在加载认证状态，显示加载界面
  if (authLoading) {
    return (
      <div className="app-loading">
        <div className="loading-content">
          <img src={faviconIcon} alt="APIViewer" className="loading-logo" />
          <h2 className="loading-title">APIViewer</h2>
          <div className="loading-spinner"></div>
          <p className="loading-text">正在加载...</p>
        </div>
      </div>
    );
  }

  // 如果未认证，显示登录页面
  if (!isAuthenticated) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  return (
    <div className="app">
      {/* 顶部Header */}
      <header className="app-header">
        <div className="header-brand">
          <img src={faviconIcon} alt="APIViewer" className="brand-logo" />
          <h1 className="brand-title">APIViewer</h1>
        </div>
        <UserInfo 
          user={currentUser} 
          onLogout={handleLogout} 
          onOpenAdminPanel={handleOpenAdminPanel}
        />
      </header>

      <div className={`app-body ${tdcMode || vesselMode ? 'fullscreen-mode' : ''}`}>
        {!tdcMode && !vesselMode && (
          <ControlPanel
            onLoadDicom={handleLoadDicom}
            onProcess={handleProcess}
            isProcessing={isProcessing}
            dicomData={dicomData}
            processedImages={processedImages}
            enableInvert={enableInvert}
            onInvertChange={handleInvertChange}
            colorMap={colorMap}
            onColorMapChange={handleColorMapChange}
            onDownloadResults={handleDownloadResults}
            enableInterpolation={enableInterpolation}
            onInterpolationChange={handleInterpolationChange}
            frameRange={frameRange}
            onFrameRangeChange={handleFrameRangeChange}
            enableVesselExtraction={enableVesselExtraction}
            onVesselExtractionChange={handleVesselExtractionChange}
            processingMethod={processingMethod}
            onProcessingMethodChange={handleProcessingMethodChange}
            hasArterialInputPoint={hasArterialInputPoint}
          />
        )}
        
        <div className="main-content">
          {error && (
            <div className="error-banner">
              <span className="error-icon">⚠️</span>
              <span className="error-text">{error}</span>
              <button 
                className="error-close"
                onClick={() => setError(null)}
              >
                ✕
              </button>
            </div>
          )}
          
          {isDownloading && (
            <div className="download-banner">
              <span className="download-icon">💾</span>
              <span className="download-text">正在生成DICOM文件...</span>
            </div>
          )}
          
          <ViewerLayout
            dicomData={dicomData}
            processedImages={processedImages}
            currentTool={currentTool}
            onToolChange={setCurrentTool}
            colorMap={colorMap}
            enableInterpolation={enableInterpolation}
            enableInvert={enableInvert}
            frameRange={frameRange}
            onVesselMaskUpdate={setCurrentVesselMask}
            onTdcModeChange={setTdcMode}
            onVesselModeChange={setVesselMode}
            processingMethod={processingMethod}
            arterialInputPoint={arterialInputPoint}
            onArterialInputPointChange={handleArterialInputPointChange}
            onTdcChartDataUpdate={handleTdcChartDataUpdate}
          />
        </div>
      </div>

      {/* 底部Footer - 现在固定显示 */}
      <footer className="app-footer">
        <div className="footer-content">
          <span className="company-name">Union Strong (Beijing) Technology Co. Ltd.</span>
          <span className="copyright">© {new Date().getFullYear()} All rights reserved.</span>
        </div>
      </footer>

      {/* 处理进度条 */}
      <ProcessingProgress
        isVisible={isProcessing}
        progress={processingProgress}
        step={processingStep}
      />

      {/* 完成提示 */}
      <CompletionToast
        isVisible={showCompletionToast}
        message="✨ 图像处理完成！所有参数计算已完成。"
        type="success"
        onClose={() => setShowCompletionToast(false)}
      />

      {/* 管理员面板 */}
      {showAdminPanel && (
        <AdminPanel 
          onClose={handleCloseAdminPanel} 
          currentUser={currentUser}
        />
      )}
    </div>
  );
}

export default App; 